Page({
  data: {
    timeStr: "2小时30分钟", // 示例字符串
    countdown: "", // 显示倒计时
    remainingSeconds: 0, // 剩余秒数
  },

  onLoad() {
    this.startCountdown(this.data.timeStr);
  },

  // 解析时间字符串并启动倒计时
  startCountdown(timeStr) {
    const totalSeconds = this.parseTimeString(timeStr);
    if (totalSeconds <= 0) return;

    this.setData({ remainingSeconds: totalSeconds });

    // 开始倒计时
    this.countdownInterval = setInterval(() => {
      let { remainingSeconds } = this.data;
      if (remainingSeconds <= 0) {
        clearInterval(this.countdownInterval);
        this.setData({ countdown: "倒计时结束" });
        return;
      }

      remainingSeconds--;
      const formattedTime = this.formatCountdown(remainingSeconds);
      this.setData({ countdown: formattedTime, remainingSeconds });
    }, 1000);
  },

  // 解析 "xx小时xx分钟" 格式的字符串，返回总秒数
  parseTimeString(timeStr) {
    let hours = 0, minutes = 0;
    const hourMatch = timeStr.match(/(\d+)小时/);
    const minuteMatch = timeStr.match(/(\d+)分钟/);

    if (hourMatch) hours = parseInt(hourMatch[1]);
    if (minuteMatch) minutes = parseInt(minuteMatch[1]);

    return hours * 3600 + minutes * 60;
  },

  // 格式化倒计时为 "xx小时xx分钟"
  formatCountdown(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    return `${hours}小时${minutes}分钟`;
  },

  onUnload() {
    clearInterval(this.countdownInterval); // 页面卸载时清除定时器
  }
});
